# models.py
# SQLAlchemy ORM模型定义
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, Float, DateTime
from sqlalchemy.orm import relationship, declarative_base
import datetime

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(32), unique=True, index=True, nullable=False)
    email = Column(String(128), unique=True, index=True, nullable=False)
    hashed_password = Column(String(128), nullable=False)
    nickname = Column(String(32), default="")
    avatar = Column(String(256), default="")
    contact = Column(String(64), default="")
    is_seller = Column(Boolean, default=False)
    cards = relationship("UserCard", back_populates="owner")
    buy_orders = relationship("Order", foreign_keys='Order.buyer_id', back_populates="buyer")
    sell_orders = relationship("Order", foreign_keys='Order.seller_id', back_populates="seller")

class Card(Base):
    __tablename__ = 'cards'
    id = Column(Integer, primary_key=True, index=True)
    code = Column(String(16), unique=True, index=True, nullable=False)  # 唯一编号，如YGO-001
    name = Column(String(64), index=True, nullable=False)
    rarity = Column(String(16), index=True)  # 稀有度
    type = Column(String(16), index=True)    # 类型：怪兽、魔法、陷阱等
    description = Column(String(256), default="")
    user_cards = relationship("UserCard", back_populates="card")

class UserCard(Base):
    __tablename__ = 'user_cards'
    id = Column(Integer, primary_key=True, index=True)
    owner_id = Column(Integer, ForeignKey('users.id'))
    card_id = Column(Integer, ForeignKey('cards.id'))
    quantity = Column(Integer, default=1)
    price = Column(Float, default=0.0)  # 售价
    owner = relationship("User", back_populates="cards")
    card = relationship("Card", back_populates="user_cards")

class Order(Base):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True, index=True)
    buyer_id = Column(Integer, ForeignKey('users.id'))
    seller_id = Column(Integer, ForeignKey('users.id'))
    user_card_id = Column(Integer, ForeignKey('user_cards.id'))
    quantity = Column(Integer, default=1)
    total_price = Column(Float, default=0.0)
    status = Column(String(16), default="pending")  # pending, paid, shipped, completed
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    buyer = relationship("User", foreign_keys=[buyer_id], back_populates="buy_orders")
    seller = relationship("User", foreign_keys=[seller_id], back_populates="sell_orders")
    user_card = relationship("UserCard")

class CartItem(Base):
    __tablename__ = 'cart_items'
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    user_card_id = Column(Integer, ForeignKey('user_cards.id'))
    quantity = Column(Integer, default=1) 